class User < ActiveRecord::Base
  attr_accessor :own_podcasts;
  
  has_many :memberships;
  has_many :podcasts, :through => :memberships;
  has_many :participations;
  has_many :episodes, :through => :participations;
  
  validates_presence_of :fullname, :username, :email, :password;
  validates_uniqueness_of :username, :email;
  validates_format_of :email, :with => /^\w+@\w+.[a-z]{2,}/;
  validates_length_of :username, :within => 1..50;
  validates_length_of :password, :within => 8..25;
  validates_length_of :fullname, :within => 1..100;
  
  before_save :adjust_podcasts_permissions;
  
  class PodcastNotAllowed < StandardError; end
  
  def own_podcasts
    @own_podcasts ||= podcasts.select{|podcast| podcast.owner?(self);};
  end
  
  protected
  def adjust_podcasts_permissions
    own_podcasts.each do |podcast|
      raise PodcastNotAllowed unless podcast.user?(self);
      podcast.owners << self;
    end 
    (podcasts - @own_podcasts).each do |podcast|
      podcast.owners.delete(self);
    end
  end
  
end